<?php

/**
 * 银行卡管理
 */
namespace app\member\api;

class CardApi extends \app\member\api\MemberApi {

    /**
     * 银行卡绑定
     */
    public function index() {
        $realInfo = target('member/MemberReal')->getWhereInfo(['A.user_id' => $this->userId]);
        $info = target('member/PayCard')->getWhereInfo(['A.user_id' => $this->userId]);
        $this->success('ok', [
            'bankList' => target('member/PayBank')->loadList(),
            'realInfo' => $realInfo,
            'info' => $info
        ]);
    }

    /**
     * 绑定银行卡
     */
    public function bind() {
        $realInfo = target('member/MemberReal')->getWhereInfo(['A.user_id' => $this->userId]);
        if(empty($realInfo)) {
            $this->error('请先认证实名信息');
        }
        $label = $this->data['label'];
        $bankInfo = target('member/PayBank')->getWhereInfo([
            'label' => $label
        ]);
        if(empty($bankInfo)) {
            $this->error('开户银行不存在！');
        }
        $userInfo = target('member/MemberUser')->getInfo($this->userId);

        $type = $this->data['valtype'];
        if (!$type) {
            $receive = $userInfo['tel'];
        } else {
            $receive = $userInfo['email'];
        }

        if (empty($receive)) {
            $this->error('该验证方式未绑定，请使用其他验证方式！');
        }

        if (!target('member/Member', 'Service')->checkVerify($receive, $this->data['code'], 2)) {
            $this->error(target('member/Member', 'Service')->getError());
        }

        $where = [];
        $where['A.user_id'] = $this->userId;
        $info = target('member/PayCard')->getWhereInfo($where);

        $this->data['name'] = $bankInfo['name'];
        $this->data['account_name'] = $realInfo['name'];
        $this->data['user_id'] = $userInfo['user_id'];
        $this->data['card_id'] = $info['card_id'];
        if(!target('member/PayCard')->saveData('edit', $this->data)) {
            $this->error(target('member/PayCard')->getError());
        }
        $this->success('银行卡保存成功！');
    }

}